import axios from "axios";
//action.type
const REGISTER_SUCCESS = 'REGISTER_SUCCESS';
const ERROR_MSG = 'ERR_MSG';

//用户初始状态
const initState = {
    msg: '',
    isAuth: false,
    user: '',
    pwd: '',
    type: ''
}

//reducer
export function user(state=initState, action) {
    switch (action.type) {
        case REGISTER_SUCCESS:
            return {
                ...state,
                msg: '',
                isAuth: true,
                ...action.payload
            }
        case ERROR_MSG:
            return {
                ...state,
                isAuth: false,
                msg: action.msg
            }
        default:
            return state
    }
}

//返回action内容
function errorMsg(msg) {
    return {
        msg,
        type: ERROR_MSG
    }
}

function registerSuccess(data) {
    return {
        type: REGISTER_SUCCESS,
        payload: data
    }
}
//action creator 发送请求并返回action结果（行动指导）
export function register({user, pwd, repeatpwd, type}) {
    if(!user||!pwd||!type) {
        return errorMsg('用户名以及密码必须输入');
    }
    if(pwd!==repeatpwd) {
        return errorMsg('两次输入的密码不相同');
    }
    return dispatch=>{
        axios.post('/user/register', {user, pwd, type}).then(
            res=>{
                if (res.status===200 && res.data.code === 0) {
                    dispatch(registerSuccess({user, pwd, type}));
                } else {
                    dispatch(errorMsg(res.data.msg));
                }
            }
        )
    }
    
}